import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

import { Message } from 'element-ui';

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: { name: 'login' }
    },
    {
      name: 'index',
      path: '/index',
      component: () => import('@/views/index.vue'),
      redirect: { path: '/index/welcome' },
      children: [
        {
          name: 'welcome',
          path: 'welcome',
          component: () => import('@/views/welcome.vue')
        },
        {
          name: 'postlist',
          path: 'postlist',
          component: () => import('@/views/postlist.vue')
        }, {
          name: 'postPublish',
          path: 'postPublish/:id?',
          component: () => import('@/views/postPublish.vue')
        }
      ]
    },
    {
      name: 'login',
      path: '/login',
      component: () => import('@/views/login.vue')
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.name == 'login') {
    next();
  } else {
    let token = JSON.parse(localStorage.getItem('hm_houtai_toutai') || "{}").token;
    if (token) {
      next();
    } else {
      Message('未登录，请先登录');
      next({ name: 'login' });
    }
  }
});

export default router;